<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
use Hyperf\HttpServer\Router\Router;


$routes = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(BASE_PATH.'/route'));

foreach ($routes as $file) {
    if ($file->getExtension() != 'php') {
        continue;
    }
	include $file->getPathname();
}

$routelist = [];
$data = Router::getData();
foreach(current($data) as $k=>$v){
	if(is_array($v)){
		foreach($v as $val){
			array_push($routelist,$val->route);
		}
	}
}


$dir_iterator = new \RecursiveDirectoryIterator(BASE_PATH.'/app/Controller');
$iterator = new \RecursiveIteratorIterator($dir_iterator);

foreach ($iterator as $file) {
	if ($file->getExtension() != 'php') {
		continue;
	}
	
	$file_path = str_replace('\\', '/',$file->getPathname());
	
	if (strpos(strtolower($file_path), 'controller.php')   === false) {
        continue;
    }
    
    $uri_path = str_replace(['/controller/', '/Controller/'], '/', substr(substr($file_path, strlen(BASE_PATH.'/app')), 0, -14));
    
    $class_name = str_replace('/', '\\',substr(substr($file_path, strlen(BASE_PATH)), 0, -4));
    
    $class_name = str_replace('app','App',$class_name);

	$class = new \ReflectionClass($class_name);
    $class_name = $class->name;
    
    $methods = $class->getMethods(\ReflectionMethod::IS_PUBLIC);
    
    $route = function ($uri, $cb) use ($routelist){
		if (in_array($uri,$routelist)) {
            return false;
        }
        Router::addRoute(['GET', 'POST','PUT','DELETE'],$uri, $cb);
        if ($uri !== '') {
            Router::addRoute(['GET', 'POST','PUT','DELETE'],$uri . '/', $cb);
        }
        $lower_uri = strtolower($uri);
        if ($lower_uri !== $uri) {
            Router::addRoute(['GET', 'POST','PUT','DELETE'],$lower_uri, $cb);
            Router::addRoute(['GET', 'POST','PUT','DELETE'],$lower_uri . '/', $cb);
        }
    };
    
    foreach ($methods as $item) {
        $action = $item->name;
        if (in_array($action, ['__construct', '__destruct'])) {
            continue;
        }
		if(is_array(config('app.app_map')) && count(config('app.app_map')) > 0){
			foreach(config('app.app_map') as $k=>$v){
				$uri_path = str_replace($k,$v,$uri_path);
			}
		}
        $route($uri_path.'/'.$action, [$class_name, $action]);
    }
}

$route('/', ['\App\\Controller\\'.config('app.default_app').'\\'.config('app.default_controller'),config('app.default_action')]);

